package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.AuthorService;
import com.heima.article.service.GeneratePageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApAuthor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;

    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Autowired
    ApArticleContentMapper apArticleContentMapper;
    @Autowired
    ApArticleMapper apArticleMapper;

    @Autowired
    AuthorService authorService;
    /**
     * 根据文章id生成文章静态页面
     * @param articleId
     */
    @Transactional
    @Async
    public void generateArticlePage(Long articleId) {
        //1.获取文章内容
        try {
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(Wrappers.<ApArticleContent>lambdaQuery()
                    .eq(ApArticleContent::getArticleId,articleId));
            if (apArticleContent != null && StringUtils.isNotBlank(apArticleContent.getContent())) {

                ApArticle apArticle = apArticleMapper.selectById(articleId);
                ApAuthor author = authorService.getById(apArticle.getAuthorId());
                //2. 模板
                Template template = null;
                template = configuration.getTemplate("article.ftl");
                //3. 数据
                Map<String, Object> params = new HashMap<>();
                params.put("content", JSONArray.parseArray(apArticleContent.getContent()));
                params.put("article", apArticle);
                params.put("authorApUserId",author.getUserId());
                StringWriter out = new StringWriter();
                template.process(params, out);
                InputStream is = new ByteArrayInputStream(out.toString().getBytes());
                //4.生成页面把html文件上传到minio中
                String path = fileStorageService.store(prefix, apArticleContent.getArticleId() + ".html","text/html", is);
                System.out.println(path);
                //5.修改ap_article表，保存static_url字段
                apArticle.setStaticUrl(path);
                apArticleMapper.updateById(apArticle);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}",articleId,e.getCause());
        }
    }
}